package com.yz.jdd.network;


import android.util.Log;

import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PreferencesUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by  lkf  on 2017/1/5.
 * Retrofit 相关
 */

public class RetrofitUtils {
    private static final Converter.Factory gsonConverterFactory = GsonConverterFactory.create();
    private static final CallAdapter.Factory rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();
    private static final int DEFAULT_TIMEOUT = 10;
    private static OkHttpClient okHttpClient;
    private static ApiObservable apiObservable;

    public static ApiObservable getApiObservable() {
        if (apiObservable == null) {
            apiObservable = getRetrofit().create(ApiObservable.class);
        }
        return apiObservable;
    }

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            synchronized (RetrofitUtils.class) {
                if (okHttpClient == null) {
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(15_000, TimeUnit.MILLISECONDS)
                            .readTimeout(15_000, TimeUnit.MILLISECONDS)
                            .writeTimeout(15_000, TimeUnit.MILLISECONDS)
                            .addInterceptor(new LogInterceptor())
                            .build();
                }
            }
        }
        return okHttpClient;
    }

    public static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .client(getOkHttpClient()).baseUrl(PreferencesUtils.getString(MyApplication.application, BaseConfigs.STRING_SERVER_URL,Constants.SERVER_URL))
                .addConverterFactory(gsonConverterFactory)
                .addCallAdapterFactory(rxJavaCallAdapterFactory)
                .build();
    }

    private static boolean isText(MediaType mediaType) {
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json") ||
                    mediaType.subtype().equals("xml") ||
                    mediaType.subtype().equals("html") ||
                    mediaType.subtype().equals("webviewhtml")
                    )
                return true;
        }
        return false;
    }

    private static String bodyToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

    private static class LogInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {

            String sessionId = PreferencesUtils.getString(MyApplication.application, BaseConfigs
                    .PREF_SESSIONID, "");

            String rc = PreferencesUtils.getString(MyApplication.application, BaseConfigs
                    .STRING_ROUTE_CODE, "");
            Request request = chain.request()
                    .newBuilder().addHeader("sessionId", sessionId)
                    .addHeader("rc",rc)
                    .build();


            long t1 = System.nanoTime();
            String requestBody = request.method().compareToIgnoreCase("post") == 0 ?
                    bodyToString(request) : "";
            String requestLog = String.format("url: %s on %s %nheaders:%n%s %nbody:%n%s",
                    request.url(), chain.connection(), request.headers(), requestBody);
            Log.e("lkf","---- request" + "\n" + requestLog);
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            String responseBody;
            boolean rebuildBody = false;
            MediaType mediaType = response.body().contentType();
            if (mediaType != null && !isText(mediaType)) {
                responseBody = "Respose Content-Type: " + mediaType.toString();
                rebuildBody = false;
            } else {
                responseBody = response.body().string();
                rebuildBody = true;
            }

            String responseLog = String.format("url: %s in %.1fms  protocol:%s %nheaders:%n%s" +
                            " " + "%nbody:%n%s", response.request().url(), (t2 - t1) / 1e6d,
                    response.protocol().name(), response.headers(), responseBody);
            Log.e("lkf","--- response" + "\n" + responseLog);

            if (rebuildBody) {
                return response.newBuilder()
                        .body(ResponseBody.create(response.body().contentType(), responseBody))
                        .build();
            } else {
                return response;
            }

        }
    }

}


